#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : 河北雪域网络科技有限公司 A.Star
# @contact: astar@snowland.ltd
# @site: www.snowland.ltd
# @file: pso_demo3.py
# @time: 2018/8/27 10:44
# @Software: PyCharm

from slapy.swarm.pso import PSOEngine
import numpy as np

# 使用前请安装文件
# pip install snowland-algorithm
# 确保版本号大于0.0.2

#  求解方程 x = sqrt(x) - x * sin(x) 在[2, 4]区间内的近似解

def fun(x):
    x = x[0]
    # 评价函数
    if 2 <= x <= 4:
        return 1 / (np.abs(x + x * np.sin(x) - np.sqrt(x)) + 1)
    else:
        return -1  # 返回一个达不到的小值


if __name__ == '__main__':
    engine = PSOEngine(dim=1, vmax=0.01, bound=[[2, 4]], min_fitness_value=-1, fitness_function=fun, steps=100)
    engine.run()
    x = engine.gbest.chromosome[0]
    print('计算得到的最大值是', fun(engine.gbest.chromosome))
    print('x取值是:', x)
